﻿using System.Collections.ObjectModel;
using System.Linq;
using System.Windows;
using System.Windows.Controls;

namespace Business
{
    public class RegionManager : Business.IRegionManager
    {
        #region Properties

        public static FrameworkElement Shell 
        {
            get 
            { 
                return Application.Current.MainWindow;
            } 
        }

        public ObservableCollection<IUIRegion> Regions { set; get; }

        #endregion

        #region Singleton Object

        private static volatile IRegionManager _instance;
        private static object syncRoot = new object();

        /// <summary>
        /// Private constructor so that nobody can create the instance
        /// </summary>
        private RegionManager()
        {
        }

        public static IRegionManager Instance
        {
            get
            {
                if (_instance == null)
                {
                    lock (syncRoot)
                    {
                        if (_instance == null)
                            _instance = GetRegionManager();
                    }
                }
                return _instance;
            }
        }

        #endregion

        #region Methods

        private static IRegionManager GetRegionManager()
        {
            IRegionManager UniqueRegions = new RegionManager();
            UniqueRegions.Regions = new ObservableCollection<IUIRegion>();
            foreach (IRole RoleRegion in User.Instance.Roles)
            {
                foreach (IRegion region in RoleRegion.Regions)
                {
                    if (UniqueRegions.Regions.FirstOrDefault(x => x.RegionID == region.RegionID && x.RegionName == region.RegionName) == null)
                    {
                        UIRegion reg = new UIRegion()
                        {
                            RegionID = region.RegionID,
                            RegionName = region.RegionName,
                            Reference = (Shell.FindName(region.RegionName)) as ContentControl
                        };
                        UniqueRegions.Regions.Add(reg);
                    }
                }
            }
            return UniqueRegions;
        }

        #endregion

    }
}
